using System.Collections.Generic;
using UnityEngine;

public class UIManager
{
    private static UIManager instance = new UIManager();
    public static UIManager Instance => instance;
    private UIManager()
    {
        //得到场景上的Canvas对象
        CanvasTransform = GameObject.Find("Canvas").transform;
        //过场景时不删除Canvas对象
        Object.DontDestroyOnLoad(CanvasTransform.gameObject);
    }
    //Canvas对象的位置信息
    private Transform CanvasTransform;
    //面板容器
    public Dictionary<string, BasePanel> panelDic = new Dictionary<string, BasePanel>();
    //显示面板,动态创建面板预设体
    public T ShowPanel<T>() where T : BasePanel
    {
        //获取传入的预设体的名字
        string panelName = typeof(T).Name;
        //判断该面板是否已经显示,如果有就不用创建了，直接返回给外部使用
        if (panelDic.ContainsKey(panelName))
            return panelDic[panelName] as T;
        //从Resources文件夹下Clone预设体
        GameObject panelObj = Object.Instantiate(Resources.Load<GameObject>("UI/" + panelName));
        //设置父对象
        panelObj.transform.SetParent(CanvasTransform, false);
        //得到对应的脚本,存储到字典中
        T panel = panelObj.GetComponent<T>();
        panelDic.Add(panelName, panel);
        //调用显示自己的逻辑
        panel.ShowMe();
        //返回
        return panel;

    }
    // 隐藏面板
    public void HidePanel<T>(bool isFade = true) where T : BasePanel
    {
        //根据泛型的类型，得到面板的名字
        string panelName = typeof(T).Name;
        //检查字典中是否包含该面板的名字（key）
        if (panelDic.ContainsKey(panelName))
        {
            if (isFade)
            {
                panelDic[panelName].HideMe(() =>
                {
                    //传入的callback函数
                    //删除对象
                    GameObject.Destroy(panelDic[panelName].gameObject);
                    //从字典中删除
                    panelDic.Remove(panelName);
                });
            }
            else
            {
                //传入的callback函数
                //删除对象
                GameObject.Destroy(panelDic[panelName].gameObject);
                //从字典中删除
                panelDic.Remove(panelName);
            }
        }
        else
        {
            Debug.Log("查找失败，找不到" + panelName);
        }
    }
    // 获取面板
    public T GetPanel<T>() where T : BasePanel
    {
        string panelName = typeof(T).Name;
        if (panelDic.ContainsKey(panelName))
            return panelDic[panelName] as T;
        //如果没有则返回null
        return null;
    }
}
